package com.space.myapollo.config;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 自定义controller拦截器，实现AbstractHandlerInterceptor即可 example
 * {@link LogUrlHandlerInterceptor}
 *
 * @version <pre>
 *          Author	Version		Date		Changes
 *          zyj 	1.0  		2018年12月2日 	Created
 *
 *                   </pre>
 * @since 1.
 */
@Configuration
public class AutoRegisterInterceptor extends WebMvcConfigurationSupport {

    @Autowired
    private ApplicationContext applicationContext;

    private Map<String, AbstractHandlerInterceptor> interceptorList;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        interceptorList = applicationContext.getBeansOfType(AbstractHandlerInterceptor.class);
        interceptorList.forEach((k, interceptor) -> {
            InterceptorRegistration registration = registry.addInterceptor(interceptor);
            registration.addPathPatterns(interceptor.getAddPathPatterns());
            registration.excludePathPatterns(interceptor.getExcludePathPatterns());
        });
    }

    /**
     * 如果继承了WebMvcConfigurationSupport，则在yml中配置的相关内容会失效
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/templates/")
                .addResourceLocations("classpath:/public/")
                .addResourceLocations("classpath:/assets/**")
                .addResourceLocations("classpath:/META-INF/spring-boot-admin-server-ui/")
                .addResourceLocations("classpath:/META-INF/spring-boot-admin-server-ui/extensions/");
        registry.addResourceHandler("swagger-ui.html")
        .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
}
